//
//  CYInvestPaymentViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/8.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYInvestPaymentViewController.h"

#import "CYSelectCardView.h"
#import "CYPaymentAffirmView.h"

#import "CYDataAPIBankCardModel.h"

#import "CYInvestSucceededViewController.h"
#import "CYBindCardViewController.h"
#import "CYWebViewController.h"
#import "CYRechargeInProgressViewController.h"

#import "CYSMSExpireManager.h"



@interface CYInvestPaymentViewController ()

@property(nonatomic, strong)UIView *topView;
@property(nonatomic, strong)UIView *topLine1;
@property(nonatomic, strong)UIView *topLine2;
@property(nonatomic, strong)UILabel *amountDescLabel;
@property(nonatomic, strong)UILabel *amountLabel;
@property(nonatomic, strong)UILabel *couponDescLabel;
@property(nonatomic, strong)UILabel *couponLabel;
@property(nonatomic, strong)UILabel *realAmountDescLabel;
@property(nonatomic, strong)UILabel *realAmountLabel;

@property(nonatomic, strong)UIView *bottomView;
@property(nonatomic, strong)UIView *bottomLine;
@property(nonatomic, strong)UILabel *balanceDescLabel;
@property(nonatomic, strong)UILabel *balanceLabel;
@property(nonatomic, strong)UILabel *cardDescLabel;
@property(nonatomic, strong)UILabel *cardLabel;

@property(nonatomic, strong)UIButton *paymentButton;
@property(nonatomic, strong)UIButton *selectCardButton;

@property(nonatomic, strong)NSArray<CYDataAPIBankCardModel *> *cardList;
@property(nonatomic, strong)CYDataAPIBankCardModel *currentCard;

@property(nonatomic, strong)NSString *mobile_auth_code;
@property(nonatomic, strong)NSString *recharge_no;

@property(nonatomic, assign)BOOL successed;

@property(nonatomic, strong)CYInvestRecordDetailViewModel *completeModel;

@end


@implementation CYInvestPaymentViewController

- (void)dealloc
{
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if(self.successed)
    {
        self.navigationController.viewControllers = @[self.navigationController.viewControllers.firstObject, self.navigationController.viewControllers.lastObject];
    }
}

- (void)close
{
    [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"返回" complete:nil];
    if(SAFE_NUMBER(self.apiModel.amountBank).integerValue > 0)
    {
        [MobClick event:UM_EVENT_0034];
    }
    else
    {
        [MobClick event:UM_EVENT_0032];
    }
    [super close];
}

- (void)loadUI
{
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillTerminateNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x) {
        [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"程序退出" complete:nil];
    }];
    
    self.navigationItem.title = @"支付";
    
    UIButton *limitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [limitButton setTintColor:HEXCOLOR(@"444444")];
    [limitButton setTitle:@"限额说明" forState:UIControlStateNormal];
    limitButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [limitButton sizeToFit];
    [limitButton addTarget:self action:@selector(onLimitButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:limitButton];
    
    self.tableView.hidden = YES;
    
    self.topView = [[UIView alloc] init];
    self.topView.backgroundColor = [UIColor whiteColor];
    self.topView.layer.masksToBounds = YES;
    self.topView.layer.cornerRadius = 4;
    [self.contentView addSubview:self.topView];
    {
        self.topLine1 = [UIView cy_lineWithColor:HEXCOLOR(@"ECECEC")];
        [self.topView addSubview:self.topLine1];
        
        self.topLine2 = [UIView cy_lineWithColor:HEXCOLOR(@"ECECEC")];
        [self.topView addSubview:self.topLine2];
        
        self.amountDescLabel = [self labelWithText:@"投资金额(元)" color:nil];
        [self.amountDescLabel sizeToFit];
        [self.topView addSubview:self.amountDescLabel];
        
        self.amountLabel = [self labelWithText:SAFE_NUMBER(self.apiModel.amount).amountString color:nil];
        [self.topView addSubview:self.amountLabel];
        
        self.couponDescLabel = [self labelWithText:@"使用优惠(元)" color:nil];
        [self.couponDescLabel sizeToFit];
        [self.topView addSubview:self.couponDescLabel];
        
        self.couponLabel = [self labelWithText:SAFE_NUMBER(self.apiModel.couponAmount).amountString color:nil];
        [self.topView addSubview:self.couponLabel];
        
        self.realAmountDescLabel = [self labelWithText:@"实付金额(元)" color:nil];
        [self.realAmountDescLabel sizeToFit];
        [self.topView addSubview:self.realAmountDescLabel];
        
        self.realAmountLabel = [self labelWithText:SAFE_NUMBER(self.apiModel.dactualAmount).amountString color:nil];
        [self.topView addSubview:self.realAmountLabel];
    }
    
    self.bottomView = [[UIView alloc] init];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    self.bottomView.layer.masksToBounds = YES;
    self.bottomView.layer.cornerRadius = 4;
    [self.contentView addSubview:self.bottomView];
    {
        self.balanceDescLabel = [self labelWithText:@"余额支付(元)" color:nil];
        [self.balanceDescLabel sizeToFit];
        [self.bottomView addSubview:self.balanceDescLabel];
        
        self.balanceLabel = [self labelWithText:SAFE_NUMBER(self.apiModel.amountWallet).amountString color:nil];
        [self.bottomView addSubview:self.balanceLabel];
        
        if(SAFE_NUMBER(self.apiModel.amountBank).integerValue > 0)
        {
            self.bottomLine = [UIView cy_lineWithColor:HEXCOLOR(@"ECECEC")];
            [self.bottomView addSubview:self.bottomLine];

            self.cardDescLabel = [self labelWithText:@"银行卡支付" color:APP_DEFAULT_COLOR_BLUE];
            [self.cardDescLabel sizeToFit];
            [self.bottomView addSubview:self.cardDescLabel];
            
            self.cardLabel = [self labelWithText:SAFE_NUMBER(self.apiModel.amountBank).amountString color:APP_DEFAULT_COLOR_BLUE];
            [self.bottomView addSubview:self.cardLabel];
            
            self.selectCardButton = [[UIButton alloc] init];
            [self.selectCardButton addTarget:self action:@selector(onSelectCardButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
            self.selectCardButton.hidden = YES;
            [self.contentView addSubview:self.selectCardButton];
        }
    }
    
    self.paymentButton = [UIButton cy_mainButtonWithTitle:SAFE_NUMBER(self.apiModel.amountBank).integerValue > 0 ? @"使用银行卡支付" : @"确认支付"];
    [self.paymentButton addTarget:self action:@selector(onPaymentButtonTouchuUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.paymentButton];
}

- (void)loadData
{
    if(SAFE_NUMBER(self.apiModel.amountBank).integerValue > 0)
    {
        [self loadDataFromServer];
    }
}

- (void)layoutUI
{
    self.topView.width = self.contentView.width - 40;
    self.topView.height = 150;
    self.topView.centerX = self.contentView.width / 2;
    self.topView.top = 10;
    {
        self.topLine1.height = 1 / SCREEN_SCALE;
        self.topLine1.width = self.topView.width - 40;
        self.topLine1.centerX = self.topView.width / 2;
        self.topLine1.centerY = self.topView.height / 3;
        
        self.topLine2.frame = self.topLine1.frame;
        self.topLine2.centerY = self.topView.height * 2 / 3;
        
        self.amountDescLabel.left = 20;
        self.amountDescLabel.centerY = self.topView.height * 1 / 5;
        
        self.couponDescLabel.left = 20;
        self.couponDescLabel.centerY = self.topView.height / 2;
        
        self.realAmountDescLabel.left = 20;
        self.realAmountDescLabel.centerY = self.topView.height * 5 / 6;
        
        [self.amountLabel sizeToFit];
        self.amountLabel.centerY = self.amountDescLabel.centerY;
        self.amountLabel.right = self.topView.width - 20;
        
        [self.couponLabel sizeToFit];
        self.couponLabel.centerY = self.couponDescLabel.centerY;
        self.couponLabel.right = self.topView.width - 20;
        
        [self.realAmountLabel sizeToFit];
        self.realAmountLabel.centerY = self.realAmountDescLabel.centerY;
        self.realAmountLabel.right = self.topView.width - 20;
    }
    
    self.bottomView.width = self.contentView.width - 40;
    self.bottomView.height = SAFE_NUMBER(self.apiModel.amountBank).integerValue > 0 ? 100 : 50;
    self.bottomView.centerX = self.contentView.width / 2;
    self.bottomView.top = self.topView.bottom + 10;
    {
        self.balanceDescLabel.left = 20;
        self.balanceDescLabel.centerY = 25;
        
        [self.balanceLabel sizeToFit];
        self.balanceLabel.centerY = self.balanceDescLabel.centerY;
        self.balanceLabel.right = self.bottomView.width - 20;

        if(SAFE_NUMBER(self.apiModel.amountBank).integerValue > 0)
        {
            self.bottomLine.height = 1 / SCREEN_SCALE;
            self.bottomLine.width = self.bottomView.width - 40;
            self.bottomLine.centerX = self.bottomView.width / 2;
            self.bottomLine.centerY = self.bottomView.height / 2;
            
            self.cardDescLabel.left = 20;
            self.cardDescLabel.centerY = 75;
            
            [self.cardLabel sizeToFit];
            self.cardLabel.centerY = self.cardDescLabel.centerY;
            self.cardLabel.right = self.bottomView.width - 20;

        }
    }
    
    self.paymentButton.width = self.contentView.width - 40;
    self.paymentButton.height = 44;
    self.paymentButton.centerX = self.contentView.width / 2;
    self.paymentButton.top = self.bottomView.bottom + 40;
    
    self.selectCardButton.width = self.paymentButton.width;
    self.selectCardButton.height = 44;
    self.selectCardButton.top = self.paymentButton.bottom + 5;
    self.selectCardButton.centerX = self.paymentButton.centerX;
}

- (void)loadDataFromServer
{
    [SVProgressHUD show];
    @weakify(self);
    [CYStandardDataAPI user_queryBindBankCardWithComplete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            self.cardList = [CYDataAPIBankCardModel mj_objectArrayWithKeyValuesArray:response.content];
            self.currentCard = self.cardList.firstObject;
            if(self.currentCard)
            {
                self.selectCardButton.hidden = NO;
                [self reloadCardButton];
            }
            [SVProgressHUD dismiss];
        }
        else
        {
            [CYStandardDataAPI user_investmentLog_addWithCode:response.code flowId:self.apiModel.operationId isSuccess:NO msg:response.message complete:nil];
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

- (void)reloadCardButton
{
    NSString *cardNumber = SAFE_STRING(self.currentCard.bankCardNo);
    if(cardNumber.length < 4)
    {
        cardNumber = @"****";
    }
    else
    {
        cardNumber = [cardNumber substringFromIndex:cardNumber.length - 4];
    }
    [self.selectCardButton setAttributedTitle:[self hintButtonAttributedStringWithDesc:[NSString stringWithFormat:@"使用%@(%@)支付，", self.currentCard.bankName, cardNumber]] forState:UIControlStateNormal];
}

#pragma mark - Actions
- (void)paymentAction
{
    if(SAFE_NUMBER(self.apiModel.amountBank).integerValue > 0)
    {
        if(self.currentCard == nil)
        {
            [MobClick event:UM_EVENT_0071];
        }
        else
        {
            [MobClick event:UM_EVENT_0035];
        }
    }
    else
    {
        [MobClick event:UM_EVENT_0033];
    }
    
    NSString *mobile = nil;
    if(SAFE_NUMBER(self.apiModel.amountBank).integerValue > 0)
    {
        if(self.currentCard == nil)
        {
            [self newCardAction];
            return;
        }
        else
        {
            if(SAFE_STRING(self.currentCard.mobile).length != 11)
            {
                [SVProgressHUD showErrorWithStatus:@"银行卡信息错误，请更换银行卡充值"];
                [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"银行卡信息错误，请更换银行卡充值" complete:nil];
                return;
            }
            else
            {
                mobile = SAFE_STRING(self.currentCard.mobile);
            }
        }
    }
    else
    {
        mobile = CYStandardAuthManager.currentAuth.mobile;
    }
    NSTimeInterval seconds = [CYStandardSMSExpireManager secondsWithType:CYSMSExpireTypePayment];
    if(seconds > 0)
    {
        [self showAffirmViewWithMobile:mobile];
        return;
    }
    @weakify(self);
    [self smsCodeActionWithComplete:^() {
        @strongify(self);
        [self showAffirmViewWithMobile:mobile];
    }];
}

- (void)showAffirmViewWithMobile:(NSString *)mobile
{
    @weakify(self);
    CYPaymentAffirmView *view = [[CYPaymentAffirmView alloc] initWithMobile:mobile];
    view.checkButton = ^(UIButton *button) {
        NSTimeInterval seconds = [CYStandardSMSExpireManager secondsWithType:CYSMSExpireTypePayment];
        if(seconds <= 0)
        {
            button.enabled = YES;
        }
        else
        {
            button.enabled = NO;
            [button setTitle:[NSString stringWithFormat:@"%.0fs后重发", seconds] forState:UIControlStateDisabled];
        }
    };
    @weakify(view);
    view.resend = ^{
        @strongify(self);
        [self smsCodeActionWithComplete:^() {
            @strongify(view);
            [view checkSeconds];
        }];
    };
    view.complete = ^(NSString *smsCode) {
        @strongify(self);
        self.mobile_auth_code = smsCode;
        [self paymentActionWithComplete:^(BOOL inProgress){
            @strongify(self);
            @strongify(view);
            [view close];
            if(inProgress)
            {
                [self inProgressAction];
            }
            else
            {
                [self successAction];
            }
        }];
    };
    [view checkSeconds];
    [view show];
}

- (void)paymentActionWithComplete:(void(^)(BOOL inProgress))complete
{
    if(self.mobile_auth_code.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入验证码" complete:nil];
        return;
    }
    [SVProgressHUD show];
    @weakify(self);
    [CYStandardDataAPI project_InvestWithMobile_auth_code:self.mobile_auth_code pay_way:self.apiModel.payWay recharge_no:self.recharge_no user_coupon_id:self.user_coupon_id complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0 || response.code == 22017)
        {
            [CYStandardSMSExpireManager resetExpireDate:[NSDate date] type:CYSMSExpireTypePayment];
            [SVProgressHUD dismiss];
            
            if(response.code == 0)
            {
                self.completeModel = [[CYInvestRecordDetailViewModel alloc] init];
                self.completeModel.progress = CYInvestProgressAccount;
                if([response.content isKindOfClass:[NSDictionary class]])
                {
                    self.completeModel.iid = SAFE_NUMBER(response.content[@"investDetailId"]);
                    NSDictionary *process = response.content[@"process"];
                    if([process isKindOfClass:[NSDictionary class]])
                    {
                        NSDate *successDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"investTime"]) doubleValue] / 1000.0];
                        NSDate *accountDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"goldTime"]) doubleValue] / 1000.0];
                        NSDate *outDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"loanTime"]) doubleValue] / 1000.0];
                        NSDate *bearingDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"interestTime"]) doubleValue] / 1000.0];
                        NSDate *inDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"repaymentTime"]) doubleValue] / 1000.0];
                        NSString *format = @"yyyy-MM-dd";
                        self.completeModel.successDate = [successDate cy_stringWithFormat:format];
                        self.completeModel.accountDate = [accountDate cy_stringWithFormat:format];
                        self.completeModel.outDate = [outDate cy_stringWithFormat:format];
                        self.completeModel.bearingDate = [bearingDate cy_stringWithFormat:format];
                        self.completeModel.inDate = [inDate cy_stringWithFormat:format];
                    }
                }
                [CYStandardDataAPI user_investmentLog_addWithCode:response.code flowId:self.apiModel.operationId isSuccess:YES msg:response.message complete:nil];
            }
            if(complete)
            {
                complete(response.code == 22017);
            }
        }
        else
        {
            [CYStandardDataAPI user_investmentLog_addWithCode:response.code flowId:self.apiModel.operationId isSuccess:NO msg:response.message complete:nil];
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

- (void)smsCodeActionWithComplete:(void(^)(void))complete
{
    [SVProgressHUD show];
    @weakify(self);
    [CYStandardDataAPI project_preInvestWithAmount:self.apiModel.amount bank_card_no:self.currentCard.bankCardNo card_no:self.currentCard.cardNo mobile:self.currentCard.mobile pay_way:self.apiModel.payWay project_id:self.fid real_name:self.currentCard.realName user_coupon_id:self.user_coupon_id complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            [SVProgressHUD dismiss];
            NSNumber *seconds = response.content[@"seconds"];
            if(![seconds isKindOfClass:[NSNumber class]])
            {
                seconds = @60;
            }
            [CYStandardSMSExpireManager resetExpireDate:[NSDate dateWithTimeIntervalSinceNow:seconds.doubleValue] type:CYSMSExpireTypePayment];
            self.recharge_no = response.content[@"rechargeNo"];
            if(complete)
            {
                complete();
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:response.message];
            [CYStandardDataAPI user_investmentLog_addWithCode:response.code flowId:self.apiModel.operationId isSuccess:NO msg:response.message complete:nil];
        }
    }];
}

- (void)selectCardAction
{
    [MobClick event:UM_EVENT_0036];
    @weakify(self);
    CYSelectCardView *view = [[CYSelectCardView alloc] initWithCardList:self.cardList title:@"选择付款方式" hasAddButton:YES];
    view.completeAction = ^(CYDataAPIBankCardModel *apiModel) {
        @strongify(self);
        self.currentCard = apiModel;
        [self reloadCardButton];
    };
    view.addCardAction = ^{
        @strongify(self);
        [self newCardAction];
    };
    [view show];
}

- (void)newCardAction
{
    CYBindCardViewController *bindCardViewController = [[CYBindCardViewController alloc] init];
    bindCardViewController.user_coupon_id = self.user_coupon_id;
    bindCardViewController.type = CYBindCardTypePayment;
    bindCardViewController.willPayment = SAFE_NUMBER(self.apiModel.amountBank);
    bindCardViewController.apiModel = self.apiModel;
    bindCardViewController.fid = self.fid;
    [self.navigationController pushViewController:bindCardViewController animated:YES];
}

- (void)successAction
{
    self.successed = YES;
    CYInvestSucceededViewController *investSucceededViewController = [[CYInvestSucceededViewController alloc] init];
    investSucceededViewController.model = self.completeModel;
    [self.navigationController pushViewController:investSucceededViewController animated:YES];
}

- (void)inProgressAction
{
    self.successed = YES;
    CYRechargeInProgressViewController *rechargeInProgressViewController = [[CYRechargeInProgressViewController alloc] init];
    rechargeInProgressViewController.type = CYRechargeInProgressTypeInvest;
    [self.navigationController pushViewController:rechargeInProgressViewController animated:YES];
}

- (void)limitAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/bank_info.html"];
    webViewController.defaultTitle = @"限额说明";
    [self.navigationController pushViewController:webViewController animated:YES];
}

#pragma mark - Control Events
- (void)onPaymentButtonTouchuUpInside
{
    [self paymentAction];
}

- (void)onSelectCardButtonTouchUpInside
{
    [self selectCardAction];
}

- (void)onLimitButtonTouchUpInside
{
    [self limitAction];
}

#pragma mark - Private Method
- (UILabel *)labelWithText:(NSString *)text color:(UIColor *)color
{
    UILabel *label = [[UILabel alloc] init];
    label.textColor = color ? color : HEXCOLOR(@"444444");
    label.font = [UIFont systemFontOfSize:14];
    label.text = text;
    return label;
}

- (NSAttributedString *)hintButtonAttributedStringWithDesc:(NSString *)desc
{
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];
    UIFont *font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    UIColor *descColor = HEXCOLOR(@"666666");
    UIColor *contentColor = APP_DEFAULT_COLOR_BLUE;
    [string appendAttributedString:[[NSAttributedString alloc] initWithString:desc ? desc : @"" attributes:@{NSFontAttributeName : font, NSForegroundColorAttributeName : descColor}]];
    [string appendAttributedString:[[NSAttributedString alloc] initWithString:@"更换" attributes:@{NSFontAttributeName : font, NSForegroundColorAttributeName : contentColor}]];
    return string;
}

@end
